import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'
import { ConfigProvider } from '@ones-design/core'
import { lifecycle, OPProvider } from '@ones-op/bridge'
import './index.css'

function App() {
  const [message, setMessage] = useState('')
  const handle = (event: MessageEvent<any>) => {
    if (typeof event.data === 'string') {
      if (event.data.startsWith('webpack')) {
        return
      }
      window.localStorage.setItem('global-banner-value', event.data)
      setMessage(event.data)
    }
  }

  useEffect(() => {
    setMessage(window.localStorage.getItem('global-banner-value') || '这是默认的公告内容')
    window.addEventListener('message', handle)
    return () => {
      window.removeEventListener('message', handle)
    }
  }, [])
  return (
    <div
      style={{
        background: '#B5A642',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '12px',
        color: '#fff',
        fontSize: '16px',
      }}
    >
      {message}
    </div>
  )
}

ReactDOM.render(
  <ConfigProvider>
    <OPProvider>
      <App />
    </OPProvider>
  </ConfigProvider>,
  document.getElementById('ones-mf-root')
)

lifecycle.onDestroy(() => {
  ReactDOM.unmountComponentAtNode(document.getElementById('ones-mf-root'))
})
